<template>
  <view class="main">
    <view class="header" style="background-color: #fc872d;color: #fff;padding: 50rpx 30rpx;">
      <view class="">
        当前账户余额
      </view>
      <view class="" style="margin-top: 20rpx;font-weight: 700;font-size: 60rpx;">
        {{storeInfo?.money||'0.00'}}
      </view>
    </view>

    <view class="content">
      <view class="tongji" style="font-size: 28rpx;color: #999;margin-top: 30rpx;">
        充值金额
      </view>
      <view class="chongzhi-box" style="margin-top: 20rpx;">
        <up-input type="number" name="" placeholder="请输入充值金额" v-model="money" style="background-color: #fff;border: 1px solid #eee;font-size: 32rpx;font-weight: 700;padding: 20rpx 20rpx;box-sizing: border-box;height: 90rpx;"></up-input>
        <up-button type="warning" style="margin-top: 150rpx;" @click="handleConfirm">确认充值</up-button>
      </view>

    </view>
    <f-pay-popup ref="payPopupRef" @success="handlePaySuccess"></f-pay-popup>
    <f-login-popup ref="loginPopupRef" />
  </view>
</template>

<script lang="ts" setup>
import { getOpenIdApi, getStoreInfoApi, storeRechargeApi } from '@/addon/htscrm/api';
import { onLoad } from '@dcloudio/uni-app';
import { nextTick, ref } from 'vue';
import FPayPopup from '@/addon/htscrm/components/f-pay-popup/index.vue';
import useAdminStore from '@/addon/htscrm/stores/admin';
import { useLogin } from '@/hooks/useLogin';
import { getAdminToken } from '@/addon/htscrm/utils/storage';
import FLoginPopup from '@/addon/htscrm/components/f-login-popup/index.vue'
import { debounce } from '@/utils/common';


const adminStore = useAdminStore()
const storeInfo = ref<any>({})
const money = ref()
const payPopupRef = ref()
const loginPopupRef = ref()
const userInfo = ref(adminStore.getUserInfo())
const login = useLogin()

onLoad(async (e:any) => {
  const { code, ...data} = e
  if(code && code !== uni.getStorageSync('wx_code')) {
      uni.setStorageSync('wx_code', code)
      getOpenId(code)
      return
  }
  
  // token 是否存在
  if(!uni.getStorageSync('openid')) {
      nextTick(() => {
          loginPopupRef.value?.open()
      })
  } else {
    getData()
  }
})

async function getOpenId(code:string) {
   const res = await getOpenIdApi({code})
   if(res.code == 1) {
    uni.setStorageSync('openid', res.data.openid)
    getData()
  }
}

async function getData() {
  console.log(uni.getStorageSync('openid'));
  
	const res = await getStoreInfoApi()
	storeInfo.value = res.data
}


const handleConfirm = debounce(async() => {
  
  if(!money.value) {
    uni.showToast({
      title: '请输入充值金额',
      icon: 'none'
    })
    return
  }

  const res = await storeRechargeApi({
    money: money.value,
    openid: uni.getStorageSync('openid')
  })
  if(res.code == 1) {
    payPopupRef.value.open(res.data)
  }
})

function handlePaySuccess() {
  getData()
}
</script>


<style scoped lang="scss">
	page {
		background-color: #f5f5f5;
	}
	.content{
		padding: 30rpx;
	}
	
</style>